<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>24位RGB转16位RGB</title>
<style>
	body {
		text-align: center;
		padding: 10%;
		font-size: 28px;
	}

	input {
		width: 30%;
		height: 28px;
		margin: 10px;
		font-size: 28px;
	}

	button {
		font-size: 28px;
		width: 50%;
		margin: 20px;
	}
</style>
<script>
	function rgb_24_to_16() {
		var in24 = document.getElementById("in").value;
		var str = "";

		// 正则校验
		var pattern = /#?[a-zA-Z0-9]{6}/;
		if(!pattern.test(in24) || in24.length > 7) {
			alert("输入长度不为6或7，请输入如：'#000000' 或 'FFFFFF'");
			return;
		}

		if(in24.length == 7) {
			// 裁掉#
			in24 = in24.substr(1, 6);
			str = "#";
		}

		// 裁剪RGB
		var r = in24.substr(0, 2);
		var g = in24.substr(2, 2);
		var b = in24.substr(4, 2);
		console.log("裁剪后16进制 r:" + r + " g:" + g + " b:" + b);

		// 16进制转10进制
		r = parseInt(r, 16);
		g = parseInt(g, 16);
		b = parseInt(b, 16);
		console.log("转10进制 r:" + r + " g:" + g + " b:" + b);

		// 移位
		r = r >> 3;
		g = g >> 2;
		b = b >> 3;
		console.log("第一次移位后 r:" + r + " g:" + g + " b:" + b);

		// 恢复高位 相加
		r = r << 11;
		g = g << 5;
		console.log("第二次移位后 r:" + r + " g:" + g + " b:" + b);
		var rgb = r + g + b;
		console.log("十进制rgb:" + rgb);

		// 十进制转十六进制
		rgb = rgb.toString(16);
		console.log("十六进制rgb:" + rgb);

		// 结果回显 rgb前补0
		document.getElementById("out").value = str + rgb.padStart(4, '0');
	}
</script>
</head>

<body>
	<div>
		<span>原理参考：https://blog.csdn.net/baidu_26678247/article/details/65629447</span>
	</div>
	<div>
		<span>24位RGB:</span>
		<input type="text" id="in" placeholder="请输入如：'#000000' 或 'FFFFFF'"/>
	</div>
	<div>
		<span>16位RGB:</span>
		<input type="text" id="out" placeholder="结果输出" />
	</div>
	<div>
		<button type="button" onclick="rgb_24_to_16()">转换</button>
	</div>
</body>
</html>